<script setup lang="js">
import { ref, toRaw } from "vue";
import TableEmpty from "@/components/TableEmpty.vue";
import { ArrowDown } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { evaluationFromRawData } from "@/apis";
import { useUserStore } from "@/store";
import { useRouter } from "vue-router";

const userStore = useUserStore();
const router = useRouter();

const tableData = ref([]);

const dataName = ref("");

const Req_info = [
  {
    label: "水厂名称",
    prop: "factory_name",
  },
  {
    label: "总投资\n(元)",
    prop: "total_invest",
  },
  {
    label: "电费\n(元)",
    prop: "ele_cost",
  },
  {
    label: "药剂费\n(元)",
    prop: "phar_cost",
  },
  {
    label: "员工成本\n(元)",
    prop: "empl_cost",
  },
  {
    label: "其他费用\n(元)",
    prop: "other_cost",
  },
  {
    label: "耗电量\n(kw·h)",
    prop: "ele_consum",
  },
  {
    label: "污水处理量\n(t)",
    prop: "wast_treat",
  },
  {
    label: "平均进水COD浓度\n(mg/L)",
    prop: "cod_in",
  },
  {
    label: "平均进水TN浓度\n(mg/L)",
    prop: "tn_in",
  },
  {
    label: "平均出水COD浓度\n(mg/L)",
    prop: "cod_out",
  },
  {
    label: "平均出水TN浓度\n(mg/L)",
    prop: "tn_out",
  },
  {
    label: "COD削减量\n(kg)",
    prop: "cod_redu",
  },
  {
    label: "氨氮削减量\n(kg)",
    prop: "nh_redu",
  },
  {
    label: "TN削减量\n(kg)",
    prop: "tn_redu",
  },
  {
    label: "TP削减量\n(kg)",
    prop: "tp_redu",
  },
  {
    label: "污泥产量\n(kg)",
    prop: "sludge_prod",
  },
];

const Opt_info = [
  {
    prop: "Glucose",
    label: "葡萄糖",
  },
  {
    prop: "Methanol",
    label: "甲醇",
  },
  {
    prop: "AceticAcid",
    label: "乙酸",
  },
  {
    prop: "SodiumAcetate",
    label: "乙酸钠",
  },
  {
    prop: "PolyaluminumChloride",
    label: "聚合氯化铝",
  },
  {
    prop: "Polyacrylamide",
    label: "聚丙烯酰胺",
  },
  {
    prop: "FerricChloride",
    label: "氯化铁",
  },
  {
    prop: "SodiumHydroxide",
    label: "氢氧化钠",
  },
  {
    prop: "HydrochloricAcid",
    label: "盐酸",
  },
  {
    prop: "CalciumHydroxide",
    label: "生石灰",
  },
  {
    prop: "SodiumBicarbonate",
    label: "碳酸氢钠",
  },
  {
    prop: "CitricAcid",
    label: "柠檬酸",
  },
  {
    prop: "SodiumHypochlorite",
    label: "次氯酸钠",
  },
  {
    prop: "LiquidChlorine",
    label: "液氯",
  },
  {
    prop: "SodiumChlorate",
    label: "氯酸钠",
  },
  {
    prop: "Ozone",
    label: "臭氧",
  },
  {
    prop: "HydrogenPeroxide",
    label: "过氧化氢",
  },
  {
    prop: "FerrousSulfate",
    label: "硫酸亚铁",
  },
  {
    prop: "SulfuricAcid",
    label: "硫酸",
  },
  {
    prop: "OtherChemicals",
    label: "其他药剂",
  },
];

const Opt_value = ref([]);

const cleanNowDataHandler = () => {
  tableData.value = [];
  ElMessage({
    type: "success",
    message: "数据已清除",
  });
};

const handlePaste = (event) => {
  const clipboardData = event.clipboardData || window.clipboardData;
  const pastedText = clipboardData.getData("Text");
  const rows = pastedText
    .trim()
    .split("\n")
    .map((row) => row.split("\t"));

  let current_header = Req_info.concat(Opt_value.value);
  console.log(current_header);
  // tableData.value.push(rows.map())
  for (let i = 0; i < rows.length; i++) {
    let inrow = {};
    inrow[[Req_info[0].prop]] = rows[i][0];
    for (let j = 1; j < rows[i].length; j++) {
      inrow[[current_header[j].prop]] = parseFloat(rows[i][j]);
    }
    tableData.value.push(inrow);
  }
};

const evaluationClickHandler = () => {
  let rawData = JSON.parse(JSON.stringify(tableData.value));
  evaluationFromRawData(rawData, userStore.UID, dataName.value).then((res) => {
    console.log(res);
    if (res?.status === 200) {
      alert(`测评成功，请查看测评码:${res?.data?.uuid}。跳转至测评结果页面`);
      router.push(`/evaluationResult/${res?.data?.uuid}`);
    } else {
      alert(`错误！请检查你的数据！`);
    }
  });
};
</script>

<template>
  <div>
    <h4>
      请按照下面的表头，将各水厂同一时期所对应的数据在excel表格中罗列好，随后复制到下面的粘贴区域即可（注：输入的数据不可为负值）。其中，化学药剂的选择应尽可能的选择各个水厂都用到的药剂，以增加水厂之间的可比性。用户可根据水厂的情况，自行选择多种药剂。固定好药剂种类后，按照表头输入数据即可开展评估。
    </h4>
    <div class="m-4" style="display: flex; justify-content: space-between">
      <div>
        <el-text class="mx-1" size="middle">选择投入的化学药剂：</el-text>
        <el-select
          v-model="Opt_value"
          value-key="prop"
          multiple
          filterable
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="3"
          placeholder="下拉选择"
          style="width: 350px"
        >
          <el-option
            v-for="item in Opt_info"
            :key="item.prop"
            :label="item.label"
            :value="item"
          />
        </el-select>
      </div>
      <div style="width: 50%">
        <el-text>评估名称：</el-text>
        <el-input
          type="text"
          v-model="dataName"
          placeholder="请输入本次评估的名称，以便查找"
          style="width: 80%"
        ></el-input>
      </div>
    </div>
    <div>
      <el-table
        :data="tableData"
        @paste.prevent="handlePaste"
        style="width: 100%; height: 90%"
        id="main-data"
        scrollbar-always-on="ture"
      >
        <template #empty>
          <table-empty></table-empty>
        </template>
        <el-table-column label="必填信息">
          <el-table-column
            v-for="column in Req_info"
            :key="column.prop"
            :label="column.label"
            :prop="column.prop"
            :show="column.show"
            v-bind="column"
            min-width="100px"
          >
          </el-table-column>
        </el-table-column>
        <el-table-column label="选填信息">
          <el-table-column
            v-for="column in Opt_value"
            :key="column.prop"
            :label="column.label"
            :prop="column.prop"
            :show="column.show"
            v-bind="column"
            min-width="80px"
          >
          </el-table-column>
        </el-table-column>
      </el-table>
    </div>
    <br />
    <div class="button-align">
      <el-button @click="evaluationClickHandler" type="success" size="large"
        >点击测评
      </el-button>
      <el-button type="danger" @click="cleanNowDataHandler" size="large"
        >清空表格
      </el-button>
    </div>
  </div>
</template>

<style scoped>
.button-align {
  display: flex;
  justify-content: center;
}

#main-data {
  width: 100% !important;
}
</style>
